package com.example.onlinetaxi.ui.activity.RouteInfoPage;

import android.graphics.Paint;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.callback.IExchangeFragments;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.util.GetCostUtil;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.TimeUtil;
import com.example.onlinetaxi.view.Dialog.TimePickerDialog;

import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class BasicInfoFragment extends Fragment {

    private View rootView;
    // 文本控件
    private TextView routeInfoStart;
    private TextView routeInfoEnd;
    private TextView routeInfoTime;
    private TextView routeInfoDistance;
    private TextView routeInfoCost;
    private TextView routeInfoUseCarTime;
    // 图片需要修改颜色
    private ImageView routeInfoBtnCar;
    // 立即打车按钮
    private LinearLayout rightNowOrderBtn;
    // 切换fragment的接口
    private IExchangeFragments iExchangeFragments;
    // 请求参数
    private Map<String, String> map = new HashMap<>();
    // 订单信息
    // 订单起点经度
    private Double longitude;
    // 订单起点纬度
    private Double latitude;
    // 订单起点位置信息
    private String startInfo;
    // 起点城市
    private String startCity;
    // 订单终点位置信息
    private String endInfo;
    // 终点城市
    private String endCity;
    // 路程预计时间(单位min)
    private Integer time;
    // 路程预计距离
    private String distance;
    // 预计费用
    private String cost;
    // 用车时间
    private String useCarTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_basic_info, container, false);

        initView();

        initEvent();

        return rootView;
    }

    private void initView() {
        // 改变按钮图片颜色
        routeInfoBtnCar = rootView.findViewById(R.id.route_info_btn_car);
        routeInfoBtnCar.setColorFilter(getResources().getColor(R.color.gray));

        // 文本控件初始化
        routeInfoStart = rootView.findViewById(R.id.route_info_start);
        routeInfoEnd = rootView.findViewById(R.id.route_info_end);
        routeInfoTime = rootView.findViewById(R.id.route_info_time);
        routeInfoDistance = rootView.findViewById(R.id.route_info_distance);
        routeInfoCost = rootView.findViewById(R.id.route_info_cost);
        routeInfoUseCarTime = rootView.findViewById(R.id.basic_info_use_car_time);

        // 添加下划线
        routeInfoUseCarTime.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

        // 获取布局按钮
        rightNowOrderBtn = rootView.findViewById(R.id.to_order_btn);
    }

    public void getRouteInfo(String startPoint, String startCity, String endPoint, String endCity, String distance, Integer time, LatLng latLng) {
        routeInfoStart.setText(startPoint);
        routeInfoEnd.setText(endPoint);
        routeInfoDistance.setText(distance + "公里");
        // 设置路程总时间
        int hours = time / 60;
        int minutes = time % 60;
        routeInfoTime.setText(hours + "小时" + minutes + "分");

        routeInfoCost.setText(GetCostUtil.getCost(distance, time));

        // 初始化订单参数
        if (latLng != null) {
            longitude = latLng.longitude;
            latitude = latLng.latitude;
        }
        startInfo = startPoint;
        this.startCity = startCity;
        endInfo = endPoint;
        this.endCity = endCity;
        this.time = time;
        this.distance = distance;
        this.cost = GetCostUtil.getCost(distance, time);
    }

    private void initEvent() {
        rightNowOrderBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到等待Fragment
                iExchangeFragments.exchangeFragment();
                // 发送订单创建请求
                if (sendOrder()) {
                    Toast.makeText(getActivity(), "正在为您叫车，请稍等！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        routeInfoUseCarTime.setClickable(true);
        routeInfoUseCarTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
    }

    private void showDialog() {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 用户此刻叫车
                // 设置文本
                routeInfoUseCarTime.setText("此 刻");
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 按照选择的时间进行叫车
                String dateStr = String.format(Locale.CHINA, "%d-%d-%d %d:%d:00",
                        TimePickerDialog.Builder.yearPicker.getValue(),
                        TimePickerDialog.Builder.monthPicker.getValue(),
                        TimePickerDialog.Builder.datePicker.getValue(),
                        TimePickerDialog.Builder.hourPicker.getValue(),
                        TimePickerDialog.Builder.minutePicker.getValue());

                // 对用车时间可行性进行判断
                if (TimeUtil.getDateDifference(new Date(), TimeUtil.StringToDate(dateStr)) == -1) {
                    // 用车时间早于当前时间
                    Toast.makeText(getActivity(), "您的预约时间不合理，请重新选择时间！", Toast.LENGTH_SHORT).show();
                } else {
                    // 设置文本
                    routeInfoUseCarTime.setText(dateStr);
                }
            }
        };

        // 显示提示框
        TimePickerDialog.showTimePickerDialog(getActivity(), onCancelClickListener, onConfirmClickListener);
    }

    // 将订单发送给后端
    private boolean sendOrder() {
        // 设置参数
        map.put("phone", LocalStorage.phone);
        map.put("longitude", longitude.toString());
        map.put("latitude", latitude.toString());
        map.put("startInfo", startInfo);
        map.put("startCity", startCity);
        map.put("endInfo", endInfo);
        map.put("endCity", endCity);
        map.put("time", time.toString());
        map.put("distance", distance);
        map.put("cost", cost);

        if (routeInfoUseCarTime.getText().toString().equals("此 刻")) {
            map.put("useCarTime", TimeUtil.DateToString(new Date()));
        } else {
            map.put("useCarTime", routeInfoUseCarTime.getText().toString());
        }

        // 发送请求
        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "order", "doOrder");
        // 获取响应体
        DataResponse dataResponse = GetDataResponse.getDataResponse(response);

        if (dataResponse.getCode().equals("200")) {
            // 获取订单编号
            LocalStorage.currentOrderId = dataResponse.getData().get("orderId").toString();

            return true;
        } else {
            // 订单出错
            Toast.makeText(getActivity(), dataResponse.getData().get("error").toString(), Toast.LENGTH_SHORT).show();

            return false;
        }

    }

    public void setiExchangeFragments(IExchangeFragments iExchangeFragments) {
        this.iExchangeFragments = iExchangeFragments;
    }
}